package com.pengtu.web.asset.equipment;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.pengtu.dao.Page;
import com.pengtu.dao.QueryFilter;
import com.pengtu.entity.app.Attachment;
import com.pengtu.entity.app.Department;
import com.pengtu.entity.asset.equipment.EquipInformation;
import com.pengtu.entity.asset.equipment.EquipItem;
import com.pengtu.service.app.AccountManager;
import com.pengtu.service.asset.EquipmentManager;
import com.pengtu.utils.ExcelHelper;
import com.pengtu.utils.reflection.ReflectionUtils;
import com.pengtu.utils.web.Struts2Utils;
import com.pengtu.web.BaseActionSupport;

@Namespace("/asset/equipment")
@Result(name = BaseActionSupport.RELOAD, location = "information.action", type = "redirect")
public class InformationAction extends BaseActionSupport<EquipInformation> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private EquipmentManager equipmentManager;
	private AccountManager accountManager;

	private String id;
	private EquipInformation equipment;
	private List<Department> deptList;
	private Page<EquipInformation> page = new Page<EquipInformation>(10);
	private List<String> itemCodes;
	private Attachment attachment;

	@Override
	public String list() throws Exception {
		// TODO Auto-generated method stub
		QueryFilter queryFilter = QueryFilter.buildFromHttpRequest(Struts2Utils
				.getRequest());
		// 设置默认排序方式
		if (!page.isOrderBySetted()) {
			page.setOrderBy("createDate");
			page.setOrder(Page.DESC);
		}
		page = equipmentManager.findFuzzyPageInformation(page, queryFilter);
		return SUCCESS;
	}

	@Override
	public String input() throws Exception {
		deptList = accountManager.getDepartment();
		if (StringUtils.isNotEmpty(id)) {
			itemCodes = equipment.getItemCodes();
		}
		return INPUT;
	}

	@Override
	public String save() throws Exception {
		// TODO Auto-generated method stub
		// 获得部门ID
		String deptId = Struts2Utils.getParameter("dept");
		// 查找并保存部门对象
		Department dept = accountManager.getDepartment(deptId);
		equipment.setDepartment(dept);
		Iterator<EquipItem> itemIterator = equipment.getItems().iterator();
		try {
			
			if(null!=itemCodes){
				while (itemIterator.hasNext()) {
					EquipItem item = itemIterator.next();
					String itemCode = item.getItemCode();

					if (!itemCodes.contains(item.getItemCode())) {
						itemIterator.remove();
					} else {
						itemCodes.remove(itemCode);
					}
				}

				// ID集合目前剩余的id均不在源集合中,创建对象,为id属性赋值并添加到源集合中.
				for (String itemCode : itemCodes) {
					EquipItem item = EquipItem.class.newInstance();
					item.setitemCode(itemCode);
					equipment.getItems().add(item);
				}
			}
		} catch (Exception e) {
			throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
		}
//		try {
//			String oldPrice  = Struts2Utils.getParameter("newPrice");
//			oldPrice = oldPrice.substring(1);
//			Double newPrice = new Double(oldPrice);
//			equipment.setPrice(newPrice);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			equipment.setPrice(0d);
//		}
		equipmentManager.saveOrUpdateInformation(equipment);
		String mes = "";
		if(StringUtils.isNotEmpty(id)){
			mes = "修改";
		}else{
			mes = "新增";
		}
		addActionMessage(mes+"名为" + equipment.getEquipmentModel() + "的设备");
		return RELOAD;
	}

	/**
	 * 
	 * importassets: 适用:从Excel导入数据保存
	 * 
	 * @return
	 * @exception
	 * @since 1.0.0
	 */
	public String importassets() {

		if (null != attachment) {
			try {
				File file = attachment.getUpfile();
				Workbook book = Workbook.getWorkbook(file);
				// 获得第一个工作表对象
				Sheet sheet = book.getSheet(0);
				int rownum = sheet.getRows(); // 得到行数
				// 得到第一列第一行的单元格
				ExcelHelper excelHelper = ExcelHelper.getInstance();
				for (int i = 2; i < rownum; i++) // 循环进行读写
				{
					if (StringUtils
							.isEmpty(excelHelper.getValueAt(sheet, i, 0)))
						continue;
					EquipInformation equipInfo = new EquipInformation();
					equipInfo.setEquipmentModel(excelHelper.getValueAt(sheet, i, 0));
					equipInfo.setEquipmentNo(excelHelper.getValueAt(sheet, i, 1));
					equipInfo.setBrand(excelHelper.getValueAt(sheet, i,2));
					try {
						Double price = new Double(excelHelper.getValueAt(sheet, i, 3));
						equipInfo.setPrice(new Double(price));
					} catch (Exception e) {
						// TODO Auto-generated catch block
						equipInfo.setPrice(0d);
					}
					equipInfo.setDataAcquisitionWorkstation(excelHelper.getValueAt(sheet, i, 4));
					equipInfo.setStored(excelHelper.getValueAt(sheet, i,5));
					// 保存部门
					String depName = excelHelper.getValueAt(sheet, i, 6);
					Department dept = accountManager.findByDepartment(
							"depName", depName);
					if (null != dept)
						equipInfo.setDepartment(dept);
					equipmentManager.saveOrUpdateInformation(equipInfo);
				}
				book.close();
			} catch (Exception e) {
				System.out.println(e);
			}
			return "successMessage";
		}
		return null;
	}

	@Override
	public String delete() throws Exception {
		addActionMessage("删除Id为" + id + "的设备");
		equipmentManager.deleteInformatin(id);
		return RELOAD;
	}

	/**
	 * 检查设备编号是否重复
	 */
	public void checkEquipNo() {
		String equipNo = Struts2Utils.getParameter("equipmentNo");
		EquipInformation mation = equipmentManager.findEquipByProperty(equipNo);
		if ((null != mation) && !(mation.getId().equalsIgnoreCase(id))) {
			Struts2Utils.renderText("false");
		} else {
			Struts2Utils.renderText("true");
		}
	}

	@Override
	protected void prepareModel() throws Exception {
		// TODO Auto-generated method stub
		if (StringUtils.isNotEmpty(id)) {
			equipment = equipmentManager.getProperty("id", id);
		} else {
			equipment = new EquipInformation();
		}
	}

	public List<Department> getDeptList() {
		return deptList;
	}

	public void setDeptList(List<Department> deptList) {
		this.deptList = deptList;
	}

	public Page<EquipInformation> getPage() {
		return page;
	}

	public void setId(String id) {
		this.id = id;
	}

	@Override
	public EquipInformation getModel() {
		// TODO Auto-generated method stub
		return equipment;
	}

	public Attachment getAttachment() {
		return attachment;
	}

	public void setAttachment(Attachment attachment) {
		this.attachment = attachment;
	}

	@Autowired
	public void setEquipmentManager(EquipmentManager equipmentManager) {
		this.equipmentManager = equipmentManager;
	}

	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	public List<String> getItemCodes() {
		return itemCodes;
	}

	public void setItemCodes(List<String> itemCodes) {
		this.itemCodes = itemCodes;
	}

}
